package com.mt.zfruitproject;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.List;

public class MyApdater extends RecyclerView.Adapter<MyApdater.MyViewHolder> {
    private Context mcontext;
    private List<Fruit> mlist;
    public MyApdater(Context context , List<Fruit> mlist) {
        this.mcontext = context;
        this.mlist = mlist;
    }

    @NonNull

    @Override
    public  MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (mcontext == null) {
            mcontext = parent.getContext();
        }
        View view = LayoutInflater.from(mcontext).inflate(R.layout.fruit_item,parent,false);
        MyViewHolder holder = new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final MyApdater.MyViewHolder holder, int position) {
        Fruit fruit = mlist.get(position);
        holder.fruitName.setText(fruit.getName());
        Glide.with(mcontext).load(fruit.getImgageId()).into(holder.fruitImage);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mlist.get(position);
                Intent intent = new Intent(mcontext, FruitActivity.class);
                intent.putExtra(FruitActivity.FRUIT_NAME, fruit.getName());
                intent.putExtra(FruitActivity.FRUIT_IMAGE_ID, fruit.getImgageId());
                mcontext.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mlist.size();
    }

  class  MyViewHolder extends RecyclerView.ViewHolder{
      CardView cardView;
      ImageView fruitImage;
      TextView fruitName;
      public MyViewHolder(View view) {
          super(view);
          cardView = (CardView) view;
          fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
          fruitName = (TextView) view.findViewById(R.id.fruit_name);
      }
  }
}
